package com.housesales.web;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import module.Employees;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import utils.PageUtil;
import bussinessService.employeesBussinessService;
import bussinessService.impl.EmployeesBussinessServiceImpl;
import domain.vo.EmployeesQueryObject;
import domain.vo.EmployeesVO;
import domain.vo.JSONObject;
import domain.vo.Message;
import exception.EmployeeNoExistException;

/**
 * 员工
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {
	private Logger logger = Logger.getLogger(EmployeeController.class);
	/**
	 * 员工业务层实现类
	 */
	private employeesBussinessService empBIS = new EmployeesBussinessServiceImpl();
	/**
	 * 员工查询对象实例
	 */
	private EmployeesQueryObject employeeQueryObject = null;

	@RequestMapping("/add")
	public String addEmployees() {
		return "/admin/employee/addUser";
	}

	/**
	 * 进入自我管理页面
	 */
	@RequestMapping("/entrySelf")
	public String entrySelf() {
		return "/admin/employee/modifyPassword";
	}

	@RequestMapping("/viewList")
	public ModelAndView viewAllList() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("admin/main");
		return mv;

	}

	@RequestMapping("/viewlistJson/{shopId}")
	public @ResponseBody
	JSONObject<EmployeesVO> viewlistJson(@RequestParam("page") int page,
			@RequestParam("rows") int rows,@PathVariable("shopId") int shopId) {
		JSONObject<EmployeesVO> jsonObject = new JSONObject<EmployeesVO>();
		List<EmployeesVO> vos = new ArrayList<EmployeesVO>();
		try {
			employeeQueryObject = new EmployeesQueryObject();
			employeeQueryObject.setShopId(shopId);
			int len = empBIS.countByQueryObject(employeeQueryObject);
			PageUtil.Page(page, rows);
			employeeQueryObject.setStart(PageUtil.start);
			employeeQueryObject.setEnd(PageUtil.end);
			vos = empBIS.getObjectByQueryObject(employeeQueryObject);
			jsonObject.setRows(vos);
			jsonObject.setTotal(len);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return jsonObject;
	}
	
	
	@RequestMapping("/getAllEmployeeJson")
	public @ResponseBody JSONObject<EmployeesVO> getBlocksJson() {
		JSONObject<EmployeesVO> jsonObject = new JSONObject<EmployeesVO>();
		
		try {
			List<EmployeesVO> tempVOS = new ArrayList<EmployeesVO>(); 
			tempVOS = empBIS.getAll();
			jsonObject.setTotal(tempVOS.size());
			jsonObject.setRows(tempVOS);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return jsonObject;
	}

	@RequestMapping("/addEmployees")
	public @ResponseBody
	Message addEmployees(HttpServletRequest request, Employees emp,
			@RequestParam("file") MultipartFile file) {
		Message message = new Message();
		try {
			emp = packageUploadFile(request, file, emp);
			empBIS.merageObject(emp);

		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			message.setErrorMsg("员工新建失败");

		} catch (IllegalStateException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			message.setErrorMsg("员工新建失败");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			message.setErrorMsg("员工新建失败");

		}

		return message;
	}

	/**
	 * 组装文件上传路径
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @param file
	 *            上传的文件
	 * @param emp
	 *            组装对象
	 * @return Employees
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	private Employees packageUploadFile(HttpServletRequest request,
			MultipartFile file, Employees emp) throws IllegalStateException,
			IOException {
		if (!file.isEmpty()) {
			// 当前服务器路径
			StringBuffer uploadPath = new StringBuffer();
			uploadPath.append(request.getSession().getServletContext()
					.getRealPath("/"));
			uploadPath.append("fileupload/");
			uploadPath.append(file.getOriginalFilename());
			File targetFile = new File(uploadPath.toString());
			file.transferTo(targetFile);
			emp.setE_photo(file.getOriginalFilename());
		}
		return emp;
	}

	@RequestMapping("/getEmployeeAll")
	public @ResponseBody
	JSONObject<EmployeesVO> getEmployeeAll() {
		JSONObject<EmployeesVO> jsonObject = new JSONObject<EmployeesVO>();
		List<EmployeesVO> vos = new ArrayList<EmployeesVO>();
		try {

			vos = empBIS.getAll();
			jsonObject.setRows(vos);
			jsonObject.setTotal(vos.size());
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return jsonObject;
	}

	@RequestMapping("/freeze/{e_sn}")
	public @ResponseBody
	Message freezeEmploye(@PathVariable("e_sn") String e_sn) {
		Message msg = new Message();
		Employees emp;
		try {
			emp = empBIS.getById(e_sn);
			emp.setE_status(Employees.Freeze);
			empBIS.merageObject(emp);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			msg.setErrorMsg("修改错误");
		}

		return msg;

	}

	@RequestMapping("/activate/{e_sn}")
	public @ResponseBody
	Message activateEmploye(@PathVariable("e_sn") String e_sn) {
		Message msg = new Message();
		Employees emp;
		try {
			emp = empBIS.getById(e_sn);
			emp.setE_status(Employees.ACTIVITY);
			empBIS.merageObject(emp);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			msg.setErrorMsg("修改错误");
		}

		return msg;

	}

	@RequestMapping("/modifyEmployees")
	public @ResponseBody
	Message modifyEmployees(HttpServletRequest request,
			@RequestParam("file") MultipartFile file) {
		Message message = new Message();
		try {
			 employeeQueryObject = new EmployeesQueryObject();
			employeeQueryObject.setE_sn(request.getSession()
					.getAttribute("e_sn").toString());
			employeeQueryObject.setE_pass(request.getParameter("old_pass"));
			employeeQueryObject.setE_status(Employees.ACTIVITY);
			Employees emp = empBIS
					.getEmployeeByQueryObject(employeeQueryObject);
			emp.setE_pass(request.getParameter("new_pass"));
			emp = packageUploadFile(request, file, emp);
			empBIS.merageObject(emp);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			message.setErrorMsg("员工更新失败");

		} catch (IllegalStateException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			message.setErrorMsg("员工更新失败");
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			message.setErrorMsg("员工更新失败");
		} catch (EmployeeNoExistException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			message.setErrorMsg("请重新填写原始密码");
		}

		return message;
	}

}
